package com.delta.rafg.core.database.impl;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import com.delta.rafg.core.database.DataHandlerOptions;
import com.delta.rafg.core.exception.RAFGException;
import com.delta.rafg.core.log.RAFGLogger;

/**
 * @author RAFG Development Team (D9127520)
 *
 */
public class OracleSeedDataHandlerImpl extends ADataHandler {

    /**
     * Holds the serial version uid.
     */
    private static final long serialVersionUID = 8169103414462620291L;

    /**
     * Holds the Path to the seed data.
     */
    private String seedPath;

    /**
     * Holds the cache Oracle Service name.
     */
    private String serviceName = "XE";

    /*
     * DataHandlerOptions.DataHandlerSpecificOptions map has the following options:
     * SeedPath    - Required   Path to load_seed_data.(bat/sh).
     * ServiceName - Optional   (default=XE) Oracle Service name.
     *
     * (non-Javadoc)
     * @see com.delta.rafg.core.database.impl.ADataHandler#initialize(com.delta.rafg.core.database.DataHandlerOptions)
     */
    @Override
    public final void initialize(final DataHandlerOptions options) throws RAFGException {
        super.initialize(options);

        if (getDataHandlerOptions().hasDataHandlerSpecificOptionsMap()) {
            seedPath = (String) getDataHandlerOptions().getDataHandlerSpecificOptionsMap().get("SeedPath");

            String overrideServiceName = (String) getDataHandlerOptions().
                       getDataHandlerSpecificOptionsMap().get("ServiceName");
            if (overrideServiceName != null) {
                serviceName = overrideServiceName;
            }
        }

        if (seedPath == null) {
            throw new RAFGException("seedPath MUST be specified so I know where to read the cache seed data from.");
        }

        loadSeedData();
    }

    @Override
    public final Connection getConnection() throws RAFGException {
        throw new java.lang.UnsupportedOperationException("getConnection() not implemented.");
    }

    @Override
    public final void closeConnection() {
        throw new java.lang.UnsupportedOperationException("closeConnection() not implemented.");
    }


    /**
     * The database seed file are batch / shell scripts to be able to load
     * the oracle tables using sqlldr.
     * @throws RAFGException RAFGException
     */
    private void loadSeedData() throws RAFGException {
        String os = System.getProperty("os.name");

        try {
            List<String> cmds = new ArrayList<String>();

            //windows
            if (os.contains("Windows")) {
                cmds.add(new File(seedPath + "/load_seed_data.bat").getCanonicalPath());
            } else {
                cmds.add(new File(seedPath + "/load_seed_data.sh").getCanonicalPath());
            }

            //add the user, pass, and service as arguments
            cmds.add(getDataHandlerOptions().getUsername());
            cmds.add(getDataHandlerOptions().getPassword());
            cmds.add(serviceName);

            ProcessBuilder pb = new ProcessBuilder(cmds);
            pb.redirectErrorStream(true);
            pb.directory(new File(seedPath));
            Process child = pb.start();
            InputStream is = child.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
              RAFGLogger.info(line);
            }
        } catch (FileNotFoundException e) {
            throw new RAFGException("File not found for creating cache: " + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //These don't apply here
	@Override
	public POLL_STYLE getPollStyle() {
		return null;
	}

	@Override
	public String getPollFrequency() {
		return null;
	}

}
